package zhongbo.java.air.airmonitor.web.websocket;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import zhongbo.java.air.airmonitor.config.RedisListenerConfig;
import zhongbo.java.air.airmonitor.listener.RedisLogChanelPublisher;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/websocket/live")
@Component
@Slf4j
public class LiveWebSocket {


    public final static ConcurrentHashMap<Session, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        sessionMap.put(session, session);
        log.info("WebSocket连接建立成功！");
    }

    @OnClose
    public void onClose(Session session) {
        sessionMap.remove(session);
        log.info("WebSocket连接关闭！");
    }

    @OnMessage
    public void onMessage(Session session, String message) {
//        redisLogChanelPublisher.publishMessage(RedisListenerConfig.LIVE_FLIGHT_PATH_ZHU, message);
        log.info("接收到客户端消息：" + message);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.info("WebSocket发生错误！");
    }


    public static void sendMessage(String message) {
        for (Session session : sessionMap.values()) {
            if (!session.isOpen()){
                continue;
            }
            synchronized (session){
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
